﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Reflection;
using Openfree.Framework.DataAccess;
using Openfree.Workflow.Common;

public partial class SiteAdmin_WorkflowCategory : SiteAdminBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            CodeConfigAccess code = new CodeConfigAccess(base.Connection);
            DataSet ds = code.LoadDataByCategory("WorkflowGroup");
            ddlGroupCode.Items.Clear();
            ddlGroupCode.DataSource = ds.Tables[0];
            ddlGroupCode.DataTextField = "CodeName";
            ddlGroupCode.DataValueField = "CodeValue";
            ddlGroupCode.DataBind();

            Assembly assembly = Assembly.Load("Openfree.Workflow");
            Type[] types = assembly.GetTypes();
            foreach (Type t in types)
            {
                if (t.FullName.IndexOf("Openfree.Workflow.Activities") > -1)
                {
                    ListItem item = new ListItem();
                    item.Text = WorkflowManager.GetActivityDescription(t);
                    item.Value = t.FullName;
                    ddlActivityType.Items.Add(item);
                }
            }

            pnlGrid.Visible = true;
            pnlEdit.Visible = false;
            string cmdText = "select a.*,b.CodeName GroupCodeName from T_WorkflowCategory a left join T_CodeConfig b on a.GroupCode=b.CodeValue and b.Category='WorkflowGroup' order by OrderIndex";
            FillGirdView(0, cmdText);
        }
        else
        {
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
        }
    }

    protected void FillGirdView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdText"].ToString();
        }
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        //成功查询出数据后缓存
        ViewState[this.ClientID + "cmdText"] = cmdText;
        gridView.ShowFooter = true;
        gridView.NavigationData = splitPage.GetNavigationData(currentPage);
        gridView.DataSource = ds.Tables[0];
        gridView.DataBind();
    }

    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[6].Text = base.FormatBoolean(e.Row.Cells[6].Text,
                "<span style='color:blue'>是</span>", "<span style='color:red'>否</span>");
        }
    }

    protected void gridView_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillGirdView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdText"].ToString());
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        ClearValue();
        hfAddOrEdit.Value = "Add";
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        imageFlow.Visible = false;
    }

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Request["CategoryID"]))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }

        hfCategoryID.Value = Request["CategoryID"];

        DataSet ds = BaseAccess.GetDataSet(base.Connection, "select * from T_WorkflowCategory where CategoryID='" + hfCategoryID.Value + "'", "T_WorkflowCategory");
        DataRow row = ds.Tables[0].Rows[0];
        tbSubject.Text = row["Subject"].ToString();
        tbOrderIndex.Text = row["OrderIndex"].ToString();
        tbDescription.Text = row["Description"].ToString();
        tbCategoryCode.Text = row["CategoryCode"].ToString();
        tbActivityPage.Text = row["ActivityPage"].ToString();
        ddlGroupCode.SelectByValue = row["GroupCode"].ToString();
        cbIsUsed.Value = row["IsUsed"].ToString();
        ds.Dispose();
        
        string imageFileName = BaseAccess.ExecuteScalar(base.Connection, "select FileName from T_Thumbnail where ForeignKey='" + hfCategoryID.Value + "' and Category='WorkflowCategory' ");
        imageFlow.Visible = true;
        imageFlow.ImageUrl = "~/PMSWeb/Photo/Workflow/" + imageFileName;


        hfAddOrEdit.Value = "Edit";
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
    }

    protected void btnRemove_Click(object sender, EventArgs e)
    {
        string ID = Request["CategoryID"];
        if (string.IsNullOrEmpty(ID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }

        string cmdText = "delete from T_WorkflowCategory where CategoryID='{0}'";
        BaseAccess.ExecuteNonQuery(base.Connection, string.Format(cmdText, ID));
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hfAddOrEdit.Value == "Add")
        {
            DataSet ds = BaseAccess.GetDataSet(base.Connection, "select * from T_WorkflowCategory where 1=2", "T_WorkflowCategory");
            DataRow row = ds.Tables[0].NewRow();
            row["CategoryID"] = Guid.NewGuid().ToString();
            row["CategoryCode"] = tbCategoryCode.Text.Trim();
            row["GroupCode"] = ddlGroupCode.SelectedValue;
            row["Subject"] = tbSubject.Text.Trim();
            row["Description"] = tbDescription.Text.Trim();
            row["OrderIndex"] = tbOrderIndex.Text.Trim();
            row["ActivityPage"] = tbActivityPage.Text.Trim();
            row["IsUsed"] = cbIsUsed.Checked;
            ds.Tables[0].Rows.Add(row);
            BaseAccess.UpdateDataSet(base.Connection, "T_WorkflowCategory", ds);
            ds.Dispose();
            ClearValue();


            if (!string.IsNullOrEmpty(fileUpload.FileName))
            {
                if (fileUpload.FileBytes.Length > ConfigManager.UploadFileSize)
                {
                    tipMessage1.ShowMessage("文件大小超过系统规定最大允许范围", 5000);
                    return;
                }
                try
                {
                    string imageID = Guid.NewGuid().ToString();
                    string fileName = fileUpload.FileName;
                    fileName = fileName.Substring(fileName.LastIndexOf('.'));
                    string file = "~/PMSWeb/Photo/Workflow/" + imageID + fileName;
                    
                    fileUpload.SaveAs(Server.MapPath(file));
                    DataSet dsThumbnail = BaseAccess.GetDataSet(base.Connection, "select * from T_Thumbnail where 1=2", "T_Thumbnail");
                    DataRow rowThumbnail = dsThumbnail.Tables[0].NewRow();
                    rowThumbnail["ImageID"] = imageID;
                    rowThumbnail["ForeignKey"] = row["CategoryID"].ToString();
                    rowThumbnail["Category"] = "WorkflowCategory";
                    rowThumbnail["FileName"] = imageID + fileName;
                    rowThumbnail["CreateUser"] = SessionManager.UserID;
                    rowThumbnail["CreateDate"] = DateTime.Now;
                    dsThumbnail.Tables[0].Rows.Add(rowThumbnail);

                    BaseAccess.UpdateDataSet(base.Connection, "T_Thumbnail", dsThumbnail);
                }
                catch (Exception ex)
                {
                    tipMessage1.ShowMessage("上传流程图文件失败:" + ex.Message, 5000);
                    return;
                }

            }
        }
        else
        {
            DataSet ds = BaseAccess.GetDataSet(base.Connection, "select * from T_WorkflowCategory where CategoryID='" + hfCategoryID.Value + "'", "T_WorkflowCategory");
            DataRow row = ds.Tables[0].Rows[0];
            row["CategoryCode"] = tbCategoryCode.Text.Trim();
            row["GroupCode"] = ddlGroupCode.SelectedValue;
            row["Subject"] = tbSubject.Text.Trim();
            row["Description"] = tbDescription.Text.Trim();
            row["OrderIndex"] = tbOrderIndex.Text.Trim();
            row["ActivityPage"] = tbActivityPage.Text.Trim();
            row["IsUsed"] = cbIsUsed.Checked;
            BaseAccess.UpdateDataSet(base.Connection, "T_WorkflowCategory", ds);
            ds.Dispose();


            if (!string.IsNullOrEmpty(fileUpload.FileName))
            {
                if (fileUpload.FileBytes.Length > ConfigManager.UploadFileSize)
                {
                    tipMessage1.ShowMessage("文件大小超过系统规定最大允许范围", 5000);
                    return;
                }
                try
                {
                    string cmdText = "delete from T_Thumbnail where ForeignKey='{0}'";
                    cmdText= string.Format(cmdText, row["CategoryID"].ToString());
                    BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
                    //todo:chairui 删除图片文件

                    string imageID = Guid.NewGuid().ToString();
                    string fileName = fileUpload.FileName;
                    fileName = fileName.Substring(fileName.LastIndexOf('.'));
                    string file = "~/PMSWeb/Photo/Workflow/" + imageID + fileName;

                    fileUpload.SaveAs(Server.MapPath(file));
                    DataSet dsThumbnail = BaseAccess.GetDataSet(base.Connection, "select * from T_Thumbnail where 1=2", "T_Thumbnail");
                    DataRow rowThumbnail = dsThumbnail.Tables[0].NewRow();
                    rowThumbnail["ImageID"] = imageID;
                    rowThumbnail["ForeignKey"] = row["CategoryID"].ToString();
                    rowThumbnail["Category"] = "WorkflowCategory";
                    rowThumbnail["FileName"] = imageID + fileName;
                    rowThumbnail["CreateUser"] = SessionManager.UserID;
                    rowThumbnail["CreateDate"] = DateTime.Now;
                    
                    dsThumbnail.Tables[0].Rows.Add(rowThumbnail);

                    BaseAccess.UpdateDataSet(base.Connection, "T_Thumbnail", dsThumbnail);
                    imageFlow.ImageUrl = file;
                }
                catch (Exception ex)
                {
                    tipMessage1.ShowMessage("上传流程图文件失败:" + ex.Message, 5000);
                    return;
                }

            }
        }
        
        tipMessage1.ShowMessage("操作成功", 5000);
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlGrid.Visible = true;
        pnlEdit.Visible = false;
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    private void ClearValue()
    {
        tbActivityPage.Text = "";
        tbCategoryCode.Text = "";
        tbDescription.Text = "";
        tbOrderIndex.Text = "";
        tbSubject.Text = "";
        cbIsUsed.Checked = false;
        ddlGroupCode.SelectedIndex = 0;
    }

    protected void btnFillTree_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(ddlActivityType.SelectedValue))
        {
            Assembly assembly = Assembly.Load("Openfree.Workflow");
            Type boj = assembly.GetType(ddlActivityType.SelectedValue);
            DataSet ds = WorkflowManager.LoadWorkflowDefinition(boj);
            treeFlow.Nodes.Clear();
            DataToTree(ds, treeFlow, null);
        }
    }

    /// <summary>
    /// 数据集转换到节点
    /// </summary>
    /// <param name="dataSet"></param>
    /// <param name="treeView"></param>
    /// <param name="node"></param>
    private void DataToTree(DataSet dataSet, TreeView treeView, TreeNode node)
    {
        String filter;
        if (node != null)
            filter = "ParentQualifiedName = '" + node.Value + "'";
        else
            filter = "ParentQualifiedName = ''";

        for (int i = dataSet.Tables[0].Select(filter, "OrderIndex desc").Length - 1; i >= 0; i--)
        {
            DataRow row = dataSet.Tables[0].Select(filter, "OrderIndex desc")[i];
            TreeNode child = new TreeNode();
            child.Value = row["QualifiedName"].ToString() + row["ParentQualifiedName"].ToString();
            child.Text = row["Description"].ToString();
            //child.NavigateUrl = "#";

            if (node != null)
            {
                node.ChildNodes.Add(child);
                if (node.Depth < 1)
                {
                    node.Expand();
                }
                else
                {
                    node.Collapse();
                }
            }
            else
                treeView.Nodes.Add(child);
            DataToTree(dataSet, treeView, child);
        }
    }
}
